﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Interface;
using DevExpress.XtraCharts;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Utils.DirectXPaint.Svg;
using System.Runtime.Serialization;

namespace Lamex.mQuality
{
    public partial class frmQC_OQA_Check_Report : frmBaseChild
    {
        string strSql;
        DataTable dt;
        string strDate_Start, strDate_End, strHNI_Month;
        string strSub_Factory, strCondition;

        public frmQC_OQA_Check_Report()
        {
            InitializeComponent();
        }

        #region 界面同步调整

        private void frmQC_OQA_Check_Report_Resize(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = splitContainerControl1.Height / 2;
            splitContainerControl2.SplitterPosition = this.Width / 2 + 4;

            splitContainerControl3.SplitterPosition = this.Width / 4;
            splitContainerControl4.SplitterPosition = this.Width / 4;
            splitContainerControl5.SplitterPosition = this.Width / 4;
        }

        //也可以用SplitterMoved事件，但SplitterMoving事件达不到效果
        private void splitContainerControl2_SplitterPositionChanged(object sender, EventArgs e)
        {
            //为简化代码及用户操作，不提供X向拖动改变布局
        }

        private void splitContainerControl4_SplitterPositionChanged(object sender, EventArgs e)
        {
            //为简化代码及用户操作，不提供X向拖动改变布局
        }

        #endregion

        private void frmQC_OQA_Check_Report_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //dateEdit1只显示年月
            dateEdit1.Properties.CalendarView = DevExpress.XtraEditors.Repository.CalendarView.Vista;
            dateEdit1.Properties.ShowToday = false;
            dateEdit1.Properties.ShowMonthHeaders = true;
            dateEdit1.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            dateEdit1.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;
            dateEdit1.Properties.Mask.EditMask = "yyyyMM";
            dateEdit1.Properties.Mask.UseMaskAsDisplayFormat = true;
            dateEdit1.EditValue = DateTime.Now;
            this.gridView1.OptionsView.ShowFooter = true;
            gridView1.Columns["产品类别"].SummaryItem.DisplayFormat = "汇总";
            gridView1.Columns["产品类别"].SummaryItem.FieldName = "";
            gridView1.Columns["产品类别"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Custom;//求和
            gridView1.Columns["检查数"].SummaryItem.DisplayFormat = "{0:0.##}";
            gridView1.Columns["检查数"].SummaryItem.FieldName = "";
            gridView1.Columns["检查数"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;//求和
            gridView1.Columns["不合格数"].SummaryItem.DisplayFormat = "{0:0.##}";
            gridView1.Columns["不合格数"].SummaryItem.FieldName = "";
            gridView1.Columns["不合格数"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;//求和
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(strDate_Start) || string.IsNullOrEmpty(strDate_End))
            {
                XtraMessageBox.Show("无法获取起始日或结束日，HNI日历未维护所选月份数据！");
                return;
            }

            //strSql = @"SELECT PRODUCT_LINE AS 产品类别,1000 AS 检查总数,SUM(ISSUE_QTY) AS 不合格数,
            //CONVERT( varchar,CONVERT(decimal(18,2),(SUM(ISSUE_QTY)/1000)*100))+'%' AS 不合格率
            //FROM QC_OQA_Issue_Record
            //WHERE CHECK_DATE>='" + strDate_Start + @"' AND CHECK_DATE<='" + strDate_End + @"'
            //GROUP BY PRODUCT_LINE";

            //dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            //gridControl1.DataSource = dt;


            List<string> lst = new List<string>();
            lst.Add(dateEdit2.Text);
            lst.Add(dateEdit3.Text);
            //show the gridview data
            DataSet ds = Lamex.Base.BaseBuildSql.GetProNameDataSet("p_QC_Issue_MonthRecordList", lst);

            double iPass = 0;
            double iFail = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                iPass += double.Parse(dr["检查数"].ToString());
                iFail += double.Parse(dr["不合格数"].ToString());
            }
            double per = iFail / iPass;
            gridView1.Columns["不合格率1"].SummaryItem.DisplayFormat = Math.Round(per * 100.0, 2).ToString() + "%";
            gridView1.Columns["不合格率1"].SummaryItem.FieldName = "";
            gridView1.Columns["不合格率1"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Custom;//求和
            //foreach(DataRow dr in ds.Tables[0].Rows)
            //{
            //    if(decimal.Parse( dr["检查数"].ToString())==0)
            //    {
            //        dr["不合格率1"] = "无检数";
            //    }
            //    if (decimal.Parse(dr["不合格数"].ToString()) == 0||string.IsNullOrEmpty(dr["不合格数"].ToString()))
            //    {
            //        dr["不合格率1"] = "无不良数";
            //    }
            //}
            gridControl1.DataSource = ds.Tables[0];
            


            ShowChart(ds.Tables[0]);
            for (int m = 0; m < gridView1.RowCount; m++)
            {
                if (decimal.Parse(gridView1.GetRowCellValue(m, "检查数").ToString()) == 0)
                {
                    gridView1.SetRowCellValue(m, "不合格率1", "无检查数");
                }
                if ( string.IsNullOrEmpty(gridView1.GetRowCellValue(m, "不合格数").ToString()))
                {
                    gridView1.SetRowCellValue(m, "不合格率1", "无不良数");

                }
                else if(decimal.Parse(gridView1.GetRowCellValue(m, "不合格数").ToString()) == 0)
                {
                    gridView1.SetRowCellValue(m, "不合格率1", "无不良数");
                }

            }
            List<IssueItem> laminateItem = new List<IssueItem>();
            List<IssueItem> panelItem = new List<IssueItem>();
            List<IssueItem> seatingItem = new List<IssueItem>();
            List<IssueItem> mggItem = new List<IssueItem>();

            //laminateItem
            foreach (DataRow dr in ds.Tables[1].Rows)
            {
                foreach (DataColumn dc in ds.Tables[1].Columns)
                {
                    if(!(dc.ColumnName == "产品类别" || dc.ColumnName == "合计" || dc.ColumnName == "检查数" || dc.ColumnName == "不良率"))
                    {
                        IssueItem model = new IssueItem();
                        model.Name = dc.ColumnName;
                        model.PreData = double.Parse( dr[dc.ColumnName].ToString());
                        if(model.PreData!=0)
                        laminateItem.Add(model);
                    }
                }
            }
            
            List<IssueItem> laminateItemOrder =laminateItem.OrderByDescending(x => x.PreData!=0).OrderByDescending(p => p.PreData).Take(3).ToList();
            if (laminateItem.Count > 3)
            {
                double laminateItemSum = laminateItem.Sum(p => p.PreData);
                IssueItem laminateModel = new IssueItem();
                laminateModel.Name = "其它";
                laminateModel.PreData = laminateItemSum - laminateItemOrder.Sum(p => p.PreData);
                laminateItemOrder.Add(laminateModel);
            }

            //panelItem
            foreach (DataRow dr in ds.Tables[2].Rows)
            {
                foreach (DataColumn dc in ds.Tables[1].Columns)
                {
                    if (!(dc.ColumnName == "产品类别" || dc.ColumnName == "合计" || dc.ColumnName == "检查数" || dc.ColumnName == "不良率"))
                    {
                        IssueItem model = new IssueItem();
                        model.Name = dc.ColumnName;
                        model.PreData = double.Parse(dr[dc.ColumnName].ToString());
                        if (model.PreData != 0)
                            panelItem.Add(model);
                    }
                }
            }
            List<IssueItem> panelItemOrder = panelItem.OrderByDescending(x => x.PreData != 0).OrderByDescending(p=>p.PreData).Take(3).ToList();
            if (panelItem.Count > 3)
            {
                double panelItemSum = panelItem.Sum(p => p.PreData);
                IssueItem panelItemModel = new IssueItem();
                panelItemModel.Name = "其它";
                panelItemModel.PreData = panelItemSum - panelItemOrder.Sum(p => p.PreData);
                panelItemOrder.Add(panelItemModel);
            }

            //seatingItem
            foreach (DataRow dr in ds.Tables[3].Rows)
            {
                foreach (DataColumn dc in ds.Tables[1].Columns)
                {
                    if (!(dc.ColumnName == "产品类别" || dc.ColumnName == "合计" || dc.ColumnName == "检查数" || dc.ColumnName == "不良率"))
                    {
                        IssueItem model = new IssueItem();
                        model.Name = dc.ColumnName;
                        model.PreData = double.Parse(dr[dc.ColumnName].ToString());
                        if (model.PreData != 0)
                            seatingItem.Add(model);
                    }
                }
            }
            List<IssueItem> seatingItemOrder = seatingItem.OrderByDescending(x => x.PreData != 0).OrderByDescending(p => p.PreData).Take(3).ToList();
            if (seatingItem.Count > 3)
            {
                double seatingItemSum = seatingItem.Sum(p => p.PreData);
                IssueItem seatingItemModel = new IssueItem();
                seatingItemModel.Name = "其它";
                seatingItemModel.PreData = seatingItemSum - seatingItemOrder.Sum(p => p.PreData);
                seatingItemOrder.Add(seatingItemModel);
            }
            //mggItem
            foreach (DataRow dr in ds.Tables[4].Rows)
            {
                foreach (DataColumn dc in ds.Tables[1].Columns)
                {
                    if (!(dc.ColumnName == "产品类别" || dc.ColumnName == "合计" || dc.ColumnName == "检查数" || dc.ColumnName == "不良率"))
                    {
                        IssueItem model = new IssueItem();
                        model.Name = dc.ColumnName;
                        model.PreData = double.Parse(dr[dc.ColumnName].ToString());
                        if (model.PreData != 0)
                            mggItem.Add(model);
                    }
                }
            }
            List<IssueItem> mggItemOrder = mggItem.OrderByDescending(x => x.PreData != 0).OrderByDescending(p => p.PreData).Take(3).ToList();
            if (mggItem.Count > 3)
            {
                double mggItemSum = mggItem.Sum(p => p.PreData);
                IssueItem mggItemModel = new IssueItem();
                mggItemModel.Name = "其它";
                mggItemModel.PreData = mggItemSum - mggItemOrder.Sum(p => p.PreData);
                mggItemOrder.Add(mggItemModel);
            }

            chartDetail(laminateItemOrder, chartControl2, "Laminate");
            chartDetail(panelItemOrder, chartControl3, "Panel");
            chartDetail(seatingItemOrder, chartControl4, "Seating");
            chartDetail(mggItemOrder, chartControl5, "MCG");
            //show the chartcontrol data

        }

        private void ShowChart(DataTable dt)
        {
            
            if (dt == null) return;
            List<string> lst = new List<string>();
            lst.Add("Laminate");
            lst.Add("Panel");
            lst.Add("Seating");
            lst.Add("MCG");
            foreach (string s in lst)
            {
                DataRow drow = dt.Select("产品类别='"+ s + "'").FirstOrDefault();
                if(drow==null)
                {
                    DataRow dr = dt.NewRow();
                    dr["产品类别"] = s;
                    dr["检查数"] = 0;
                    dr["不合格率"] = 0;
                    dr["不合格率1"] = "0%";
                    dt.Rows.Add(dr);
                }
            }
            DataTable dtCopy = dt.Copy();

            DataView dv = dt.DefaultView;
            dv.Sort = "产品类别";
            dtCopy = dv.ToTable();

            decimal cumSumRMB = 0;
            decimal cumSumTP = 0;
            chartControl1.Series.Clear();
            

            if (dtCopy.Rows.Count > 1)
            {
                //DataTable dataList = dataView.ToTable(true, "产品类别");

                Series seriesline = new Series("检查数", ViewType.Bar);
                Series series = new Series("不合格率", ViewType.Line);

                seriesline.DataSource = dtCopy;

                chartControl1.Series.Add(seriesline);
                SetSeries(seriesline, "产品类别", new string[] { "检查数" });

                LineSeriesView lineView = (LineSeriesView)series.View;
                lineView.Color = Color.Blue;


                series.DataSource = dt;
                chartControl1.Series.Add(series);
                SetSeries(series, "产品类别", new string[] { "不合格率" });
                LineSeriesView LineView1 = (LineSeriesView)series.View;
                LineView1.Color = Color.Green;
                series.CrosshairLabelPattern = "{ A: yyyy - M - d}：{V:0.00%}";
                
                //setting show percent 
                seriesline.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
                series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
                //add y axis show
                XYDiagram diagramhour = (XYDiagram)chartControl1.Diagram;
                diagramhour.SecondaryAxesY.Clear();
                SecondaryAxisY AxisY = new SecondaryAxisY();
                AxisY.Label.TextPattern = "{V:0.00%}";
                diagramhour.SecondaryAxesY.Add(AxisY);
                ((LineSeriesView)series.View).AxisY = AxisY;
                //series title positive setting
                Legend Legends = (Legend)chartControl1.Legend;
                Legends.Visibility = DevExpress.Utils.DefaultBoolean.True;
                Legends.AlignmentVertical = LegendAlignmentVertical.TopOutside;
                Legends.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
                Legends.Direction = LegendDirection.LeftToRight;
                Legends.TextVisible = true;
                diagramhour.AxisY.ConstantLines.Clear();

                BarSeriesLabel point = (BarSeriesLabel)seriesline.Label;
                point.Position = BarSeriesLabelPosition.TopInside;
                //ConstantLine constantLineligh1 = new ConstantLine("目标" + trackBarControl1.Value + "%", Math.Round(double.Parse(trackBarControl1.Value.ToString()) / 100.0, 2));

                //constantLineligh1.Color = Color.Red; //直线颜色
                //constantLineligh1.Title.TextColor = Color.Green;   //直线文本字体颜色  
                //constantLineligh1.Title.Alignment = ConstantLineTitleAlignment.Near;
                //constantLineligh1.Title.Visible = true;
                //constantLineligh1.ShowInLegend = false;
                //diagramhour.AxisY.ConstantLines.Add(constantLineligh1);

                //diagramhour.AxisY.WholeRange.MaxValue = 1.2;

                // 横标题设置
                //chartControl1.Titles.Clear();
                //ChartTitle titles = new ChartTitle();            //声明标题
                //titles.Text = "Comp Cost% Trend";                            //名称
                //                                                             //titles.TextColor = System.Drawing.Color;   //颜色
                //titles.Indent = 1;                                //设置距离  值越小柱状图就越大
                //titles.Font = new Font("Tahoma", 12, FontStyle.Bold);            //设置字体
                //titles.Dock = ChartTitleDockStyle.Top;           //设置对齐方式
                //titles.Indent = 0;
                //titles.Alignment = StringAlignment.Center;       //居中对齐
                //chartControl1.Titles.Add(titles);                 //添加标题  
            }
        }
        /// <summary>
        /// 设置Series 的属性
        /// </summary>
        /// <param name="ser"></param>
        /// <param name="argumentDataMember"></param>
        /// <param name="valueDataMember"></param>
        private void SetSeries(Series series, string argumentDataMember, string[] valueDataMember)
        {
            // setting X  axis type
            series.ArgumentScaleType = ScaleType.Qualitative;
            //show information and data
            series.PointOptions.PointView = PointView.Values;
            // setting X axis bind field
            series.ArgumentDataMember = argumentDataMember;
            series.ValueScaleType = ScaleType.Numerical;
            // setting Y axis bind field
            series.ValueDataMembers.AddRange(valueDataMember);
            // show lable data
            series.Label.Visible = true;


            
        }
        //load all factory detail data and show
        private void chartDetail(List<IssueItem> lst , ChartControl chart, string factoryName)
        {
            chart.Series.Clear();
            if(factoryName== "Laminate")
            {
                if (lst.Count == 0)
                {
                    lbl_Laminate.Visible = true;
                    return;
                }
                else
                    lbl_Laminate.Visible = false;
            }
            else if (factoryName == "Panel")
            {
                if (lst.Count == 0)
                {
                    lbl_Panel.Visible = true;
                    return;
                }
                else
                    lbl_Panel.Visible = false;
            }
            else if (factoryName == "Seating")
            {
                if (lst.Count == 0)
                {
                    lbl_Seating.Visible = true;
                    return;
                }
                else
                    lbl_Seating.Visible = false;
            }
            else if (factoryName == "MCG")
            {
                if (lst.Count == 0)
                {
                    lbl_MCG.Visible = true;
                    return;
                }
                else
                    lbl_MCG.Visible = false;
            }
            Series seriesAuto = new Series(factoryName, ViewType.Pie);
            double dt3Sum = lst.Select(p => p.PreData).Sum();
            foreach (IssueItem item in lst)
            {
                
                //dr["Title"] = percent;
                SeriesPoint p = new SeriesPoint();

                double[] d = new double[] { double.Parse(Math.Round((item.PreData / dt3Sum) * 100, 2).ToString()) };
                p.Values = d;
                string percentName = item.Name + ": "+ item.PreData + "PCS(" + Math.Round((item.PreData / dt3Sum) * 100, 2).ToString() + " % " + ")"; 
                p.Argument = percentName;
                seriesAuto.Points.Add(p);

            }
            chart.Series.Add(seriesAuto);
            seriesAuto.Label.Font = new System.Drawing.Font("Tahoma", 8F);
            seriesAuto.PointOptions.PointView = PointView.Argument;
            seriesAuto.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;

            //series title positive setting
            Legend Legends = (Legend)chart.Legend;
            Legends.Visibility = DevExpress.Utils.DefaultBoolean.False;
            Legends.AlignmentVertical = LegendAlignmentVertical.TopOutside;
            Legends.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
            Legends.Direction = LegendDirection.LeftToRight;
            Legends.TextVisible = false;
        }
        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {

            #region 初始化界面图表

            dateEdit2.EditValue = null;
            dateEdit3.EditValue = null;
            strDate_Start = "";
            strDate_End = "";

            gridView1.OptionsBehavior.Editable = false;
            gridControl1.DataSource = null;

            chartControl1.Series.Clear();
            chartControl2.Series.Clear();
            chartControl3.Series.Clear();
            chartControl4.Series.Clear();
            chartControl5.Series.Clear();

            #endregion

            //首先判断数据库是否有dateEdit1.Text，再取TOP 2
            if (string.IsNullOrEmpty(dateEdit1.Text))
            {
                return;
            }

            DataTable dt1 = Lamex.Base.BaseBuildSql.GetDataTableBySql("select top 2 * from Cost_HNI_Calendar where YEAR_MONTH='" + dateEdit1.Text + "'  order by YEAR_MONTH");////AAA

            if (dt1.Rows.Count == 0)
            {
                return;
            }
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql("select top 2 * from Cost_HNI_Calendar where YEAR_MONTH>='" + dateEdit1.Text + "'  order by YEAR_MONTH");
            if (dt.Rows.Count == 2)
            {
                strDate_Start = dt.Rows[0]["FIRST_DATE"].ToString();
                strDate_End = Convert.ToDateTime(dt.Rows[1]["FIRST_DATE"].ToString()).AddDays(-1).ToString("yyyy-MM-dd");
                dateEdit2.DateTime = Convert.ToDateTime(strDate_Start);
                dateEdit3.DateTime = Convert.ToDateTime(strDate_End); ;
            }
            else
            {
                XtraMessageBox.Show("无法获取起始日或结束日，HNI日历未维护所选月份数据！");
                return;
            }
        }

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            //Lamex.Common.ExecelHelper.GridViewToExcel(vGridControl1);
            base.DoExport(sender);
        }
    }

   public class IssueItem
    {
        private string _Name ="";
        private double _PreData = 0;
        [DataMember]
        public string Name
        {
            get
            {
                return this._Name;
            }
            set
            {
                this._Name = value;
            }
        }
        [DataMember]
        public double PreData
        {
            get
            {
                return this._PreData;
            }
            set
            {
                this._PreData = value;
            }
        }
    }
}